#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

enum direction
{
    Up, Down, Left, Right
};
typedef enum direction Direction;

struct snake_state
{
    int snake_body[20][20];
    int snake_length;
    int food_x, food_y;
    int snake_start_x, snake_start_y;  //初始位置
    int snake_tail_x, snake_tail_y;  //结束位置
    int score;
    int level;
    int game_state;
    int running;
    Direction direction;
};
typedef struct snake_state Game;

Game game;

int init_game()
{
    game.game_state = 1;
    game.running = 1;
}

int game_over()
{
    //撞墙壁，假设游戏区域是20*20
    if (game.snake_body[0][0]<0 || game.snake_body[0][0]>=20 || game.snake_body[0][1]<0 || game.snake_body[0][1]>=20)
    {
        return  1;
    }
    //撞自己
    for (int i = 1; i < game.snake_length; i++)
    {
        if (game.snake_body[0][0] == game.snake_body[i][0] && game.snake_body[0][1] == game.snake_body[i][1])
        {
            return 1;
        }
    }
    return  0;
}

int handle_input()
{
    char ch;
    //设置终端为非阻塞模式（快速读取按键）
    struct termios oldt, newt;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    //尝试读取按键
    if (read(STDIN_FILENO, &ch, 1) >0)
    {
        if (ch == ' ')
        {
            game.game_state != game.game_state;
        }else if (ch ==27)//esc的ASCII值是27
        {
            game.running = 0;
        }
        tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    }

}

void check_food()
{
    if (game.snake_body[0][0] == game.food_x && game.snake_body[0][1] == game.food_y)
    {
        //得分加10
        game.score +=10;
        //生成新的食物
        //generate_fodd()
        //蛇的长度增加
        game.snake_length++;
    }
}